//
//  HUCreateQRCode.m
//  二维码扫描
//
//  Created by hu on 16/5/16.
//  Copyright © 2016年 hu. All rights reserved.
//

#import "HUCreateQRCode.h"

@interface HUCreateQRCode ()

@end

@implementation HUCreateQRCode

+ (UIImage *)createQRCodeImageWithString:(NSString *)string withIconImage:(UIImage *)iconImage {
    //二维码滤镜
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    //恢复滤镜的默认属性
    [filter setDefaults];
    //将字符串转换成NSData
    NSData *data=[string dataUsingEncoding:NSUTF8StringEncoding];
    //通过KVO设置滤镜inputmessage数据
    [filter setValue:data forKey:@"inputMessage"];
    //获得滤镜输出的图像
    CIImage *outputImage=[filter outputImage];
    //将CIImage转换成UIImage,并放大显示
    UIImage* QRImage = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:1000.0];
    if (iconImage) {
        return [self composeImage:QRImage secondImage:iconImage];
    }else
        return QRImage;
}
//改变二维码大小
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}
//两张图片的融合
+ (UIImage *)composeImage:(UIImage*)firstImage secondImage:(UIImage*)secondImage{
    CGSize size = firstImage.size;
    CGFloat sizeValue = size.width / 4 ;
    UIGraphicsBeginImageContext(firstImage.size);
    [firstImage drawInRect:CGRectMake(0, 0, firstImage.size.width, firstImage.size.height)];
    [secondImage drawInRect:CGRectMake((size.width - sizeValue) / 2, (size.width - sizeValue) / 2, sizeValue, sizeValue)];
    
    UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resImage; 
}
@end
